package com.wangpu.oa.web.servlet;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wangpu.oa.Application;
import com.wangpu.oa.dao.DaoFactory;
import com.wangpu.oa.dao.UserDao;
import com.wangpu.oa.dto.JSONResponse;
import com.wangpu.oa.exception.OAException;
import com.wangpu.oa.util.JSONUtil;
import com.wangpu.oa.util.SystemUtil;
@WebServlet("/api/system/statistics")
public class Statisticservlet extends HttpServlet{
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		JSONResponse result=new JSONResponse();
		try {
			UserDao udao=DaoFactory.getDao(UserDao.class);
			int onlineUsers=Application.ONLINE_USER_COUNT;
			//int totalAccount=udao.statisticsTotalAccount();
			double cpuPayload=SystemUtil.getCpuRatioForWindows();
			double memoryPayload=(long) SystemUtil.getMemery();
	        Map<String, Object> statiscs=new HashMap<>();
	        
	        statiscs.put("onlineUsers", onlineUsers);
	        //statiscs.put("totalAccount", totalAccount);
	        statiscs.put("cpuPayload", cpuPayload+"%");
	        statiscs.put("memoryPayload", memoryPayload+"%");
			result.setCode("ok");
			result.setData(statiscs);
		} catch (OAException e) {
			result.setCode("0001");
			result.setMessage(e.getMessage());
		} catch (Exception e) {
			result.setCode("error");
			result.setMessage("系统繁忙，请稍候再试!");
			//打印异常信息，用于调试
			e.printStackTrace();
		} finally {
			Writer out=resp.getWriter();
			out.write(JSONUtil.toJsonString(result));
			out.close();
		}
	}
}
